<!--
 @description 经销商解冻/冻结-编辑
 @fileName Add.vue
 @author zengqiongying
 @created 2023-04-26 20:41:28
-->
<template>
  <div class="has-foot-pb">
    <Card>
      <DealerCell :detail="dealerData">
        <div style="margin-top: 8px" :class="{ 'color-org': typeCode === 'E', 'color-normal': typeCode === 'F' }">
          经销商{{ typeCode === 'F' ? '解冻' : '冻结' }}
        </div>
      </DealerCell>
    </Card>
    <Card>
      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        :required="false"
      />
      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="dealerData.officeCode && detail.customerCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />

        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>

    <Card>
      <!-- <FieldPicker
        v-model="freezeDTO.reportType"
        title="提报类型"
        :url="`/data-dict/app/v2/dictionary/CTM_REPORT_TYPE`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
        required
      /> -->
      <Cell :modelValue="freezeDTO.reportType" title="提报类型" dictTypeCode="CTM_REPORT_TYPE" readonly required />
      <FieldPicker
        v-model="freezeDTO.type"
        :title="`${typeName}类型`"
        :url="`/data-dict/app/v2/dictionary/CTM_FREEZE_UNFREEZE_TYPE`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
        :required="false"
        @change="handleChangeType"
      />

      <FieldPicker
        v-if="freezeDTO.type === 'D'"
        v-model="freezeDTO.subType"
        :title="`${typeName}细分类型`"
        :url="`/data-dict/app/v2/dictionary/CTM_UNFREEZE_SUB_TYPE`"
        method="get"
        label-name="dictName"
        value-name="dictCode"
        :params="dictParams"
        required
        clear
        :includes="['A', 'B']"
      />

      <FieldPicker
        v-if="freezeDTO.type === 'E'"
        v-model="freezeDTO.subType"
        :title="`${typeName}细分类型`"
        :url="`/data-dict/app/v2/dictionary/CTM_UNFREEZE_SUB_TYPE`"
        method="get"
        label-name="dictName"
        value-name="dictCode"
        :params="dictParams"
        required
        clear
        :includes="['C', 'D', 'E']"
      />
      <FieldDateTime
        v-model="freezeDTO.executeTime"
        title="首次执行时间"
        placeholder="请选择日期"
        type="date"
        :default-date="freezeDTO.executeTime"
        :max-date="maxDate"
        :min-date="minDate"
        :required="false"
        clear
      />
      <template v-if="typeCode === 'F'">
        <Cell title="是否临时解冻" custom :right="false" divider required>
          <qmp-switch v-model="freezeDTO.isTempUnfreeze">
            <template #background>
              <span class="qmp-switch__background"> {{ freezeDTO.isTempUnfreeze ? '是' : '否' }}</span>
            </template>
          </qmp-switch>
        </Cell>
        <FieldDateTime
          v-if="freezeDTO.isTempUnfreeze"
          v-model="freezeDTO.preCloseTime"
          title="预计关闭时间"
          placeholder="请选择时间"
          type="datetime"
          :default-date="freezeDTO.preCloseTime"
          :max-date="maxDate"
          :min-date="minDate"
          required
          clear
        />
      </template>

      <Cell :title="`${typeName}原因`" is-column custom divider :right="false" :required="false">
        <qmp-field v-model="freezeDTO.cause" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
      <Cell title="备注" is-column custom divider :right="false">
        <qmp-field v-model="freezeDTO.remark" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>

    <Card v-if="typeCode === 'F'">
      <Cell title="是否涉及报图" custom :right="false" divider>
        <qmp-switch v-model="freezeDTO.isInvolveReportPic">
          <!-- @update:model-value="onUpdateValue" -->
          <template #background>
            <span class="qmp-switch__background"> {{ freezeDTO.isInvolveReportPic ? '涉及' : '不涉及' }}</span>
          </template>
        </qmp-switch>
      </Cell>
      <template v-if="freezeDTO.isInvolveReportPic">
        <FieldDateTime
          v-model="freezeDTO.lastReportPicTime"
          title="报图时间"
          sub-title="涉及报图需要填写"
          placeholder="选择报图日期"
          type="date"
          :default-date="freezeDTO.lastReportPicTime"
          :max-date="maxDate"
          :min-date="minDate"
          clear
        />
        <Cell
          title="报图面积(㎡)"
          sub-title="涉及报图需要填写"
          v-model="freezeDTO.lastReportPicArea"
          is-input
          placeholder="输入报图面积"
          input-align="right"
          :right="false"
        />
        <!-- :required="!!freezeDTO.isInvolveReportPic" -->
      </template>
    </Card>
    <Card v-if="typeCode === 'F'">
      <Cell title="是否涉及整改保证金" custom :right="false">
        <qmp-switch v-model="freezeDTO.isInvolveDeposit">
          <template #background>
            <span class="qmp-switch__background"> {{ freezeDTO.isInvolveDeposit ? '涉及' : '不涉及' }}</span>
          </template>
        </qmp-switch>
      </Cell>
    </Card>

    <Card :title="`选择${typeName}账号`">
      <div class="account-list">
        <qmp-checkbox-group v-model="checkedAccountCodes">
          <qmp-checkbox
            v-for="(item, i) in accountList"
            :key="i"
            :name="item.accountCode"
            :disabled="getCheckDisable(item.state)"
          >
            <div class="account-item">
              <div class="title">
                <span class="tag">{{ item.accountTypeName }}</span>
                <span class="code">{{ item.accountCode }}</span>
                <span
                  class="state"
                  :class="{
                    'color-error': item.state === 1,
                    'color-normal': item.state === 0
                  }"
                >
                  {{ item.state === 1 ? '冻结中' : '正常使用' }}
                </span>
              </div>
              <div class="address">{{ item.accountName }}</div>
            </div>
          </qmp-checkbox>
        </qmp-checkbox-group>
      </div>
    </Card>
    <Card v-if="detail.type" :title="`${typeName}附件`" :class="{ requiredClass: attrachRequired }">
      <Cell is-column custom :right="false" :required="attrachRequired">
        <AttachmentUpload
          v-model="attrFileList"
          :objectId="id"
          :type-code="detail.type === 'E' ? 'ACCESS073' : 'ACCESS074'"
        />
      </Cell>
    </Card>

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-warning" @click="onSave('B')">提交</div>
      <div class="btn radius-larg ctm-btn-main" @click="onView">预览</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSave('A')">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed, watch, onActivated } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import DealerCell from '@/components/DealerCell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import FieldPicker from '@/components/FieldPicker/index.vue'
  import FieldDateTime from '@/components/FieldDateTime/index.vue'
  import AttachmentUpload from '@/components/AttachmentUpload/index.vue'
  import { detail, saveOrSubmit } from '@/apis/dealerMarketing/FreezeAndthaw'
  import { initFormData, parseTime } from '@/utils'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerFreezeAndthawEdit',
    components: { Card, Cell, DealerCell, FieldSelect, FieldPicker, FieldDateTime, AttachmentUpload },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },

        maxDate: new Date(),
        minDate: new Date(),
        nowDate: new Date(),
        detail: {
          type: ''
        },
        formData: {
          id: '',
          code: '', //单据编号
          type: '', //类型：F 解冻， E 冻结
          subType: '', // 细分类型
          isOtherReceiveManagerKnow: '0',
          receiveManagerCode: '', // 接收客户经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeCode: '',
          receiveManagerTypeName: '',
          submitAnOpinion: ''
        },
        freezeDTO: {
          changeCode: '',
          reportType: '',
          type: '',
          reason: '',
          remark: '',
          isInvolveDeposit: false,
          isInvolveReportPic: false,
          lastReportPicArea: '',
          lastReportPicTime: '',
          executeTime: '', // 首次执行时间
          isTempUnfreeze: '', //是否临时解冻
          preCloseTime: '' // 预计关闭时间
        },
        checkedAccountCodes: [],
        attrFileList: [] // 附件
      })
      datas.keyboard = {
        show: false
      }
      datas.keyboard = GetKeyboardMixin()

      // 单据类型
      const typeCode = computed(() => {
        return datas.detail?.type || ''
      })
      // 单据类型
      const typeName = computed(() => {
        return typeCode.value === 'F' ? '解冻' : typeCode.value === 'E' ? '冻结' : ''
      })
      // 当且仅当解冻类型选择非公司品牌类和违价类时，解冻附件设置为必填
      const attrachRequired = computed(() => {
        const whiteList = ['A', 'D']
        return (typeCode.value === 'F' && whiteList.includes(datas.freezeDTO.type)) || false
      })

      const dealerData = computed(() => {
        const d = { ...datas.detail }
        return {
          code: d.customerCode || '',
          name: d.customerName || '',
          officeCode: d.officeCode || '',
          officeName: d.officeName || '',
          createBy: d.createBy || ''
        }
      })
      const accountList = computed(() => {
        return datas.detail?.rangeDTOS || []
      })

      const setPageTitle = () => {
        if (!['E', 'F'].includes(datas.detail.type)) return
        proxy.$SimpleEvents.emit('routeMetaTitle', datas.detail.type === 'F' ? '解冻编辑' : '冻结编辑')
      }

      onActivated(() => {
        setPageTitle()
      })

      watch(
        () => datas.detail.type,
        () => {
          setPageTitle()
        }
      )

      const getFormData = () => {
        const { formData, freezeDTO, attrFileList }: any = datas

        let data: anyObjectModle = {
          ...formData,
          freezeDTO: JSON.parse(JSON.stringify(freezeDTO))
        }

        data.freezeDTO.isInvolveDeposit = freezeDTO.isInvolveDeposit ? 1 : 0
        data.freezeDTO.isInvolveReportPic = freezeDTO.isInvolveReportPic ? 1 : 0
        data.freezeDTO.isTempUnfreeze = freezeDTO.isTempUnfreeze ? 1 : 0

        if (attrFileList.length > 0) {
          data.attachmentDTOS = attrFileList.map((v: any) => {
            return {
              ...v,
              ...{ modelId: data.id }
            }
          })
        }
        const checkedCodes = datas.checkedAccountCodes
        data.rangeDTOS = accountList.value.map((v: any) => {
          let isChange = v.isChange
          if (checkedCodes.includes(v.accountCode)) {
            // 已选中的
            isChange = 1
          }
          return {
            ...v,
            ...{ isChange, changeCode: data.code }
          }
        })
        return data
      }

      const onSave = (schedule: string, callback: any) => {
        const data: anyObjectModle = getFormData()
        if (schedule === 'B') {
          if (none.includes(data.isOtherReceiveManagerKnow)) {
            // proxy.$toast('请选择是否需要其他业务客户经理接收知晓')
            // return
          } else {
            if ([1, '1'].includes(data.isOtherReceiveManagerKnow)) {
              if (none.includes(data.receiveManagerCode)) {
                proxy.$toast('请选择接收客户经理')
                return
              }
            }
          }
          const rangeDTOSChange = data.rangeDTOS.some((v: any) => !!v.isChange)
          if (!rangeDTOSChange) {
            proxy.$toast(`请选择至少一个${datas.detail?.schedule === 'F' ? '解冻' : '冻结'}账号`)
            return
          }
          if (data.freezeDTO) {
            const d = data.freezeDTO
            d.cause = `${d.cause}`.trim()
            d.remark = `${d.remark}`.trim()
            /* if (none.includes(d.cause)) {
              proxy.$toast('请输入原因')
              return
            }
            if (none.includes(d.type)) {
              proxy.$toast(`请选择${datas.detail?.schedule === 'F' ? '解冻' : '冻结'}类型`)
              return
            } */

            if ((d.type === 'D' || d.type === 'E') && none.includes(d.subType)) {
              proxy.$toast(`请选择${datas.detail?.schedule === 'F' ? '解冻' : '冻结'}细分类型`)
              return
            }
            /* if (none.includes(d.executeTime)) {
              proxy.$toast('请选择首次执行时间')
              return
            } */

            if ([1, '1'].includes(d.isTempUnfreeze)) {
              if (none.includes(d.preCloseTime)) {
                proxy.$toast('请选择预计关闭时间')
                return
              }
            } else {
              data.preCloseTime = ''
            }

            if ([1, '1'.includes(d.isInvolveReportPic)]) {
              // 是否涉及报图
              /* if (none.includes(d.lastReportPicTime)) {
                proxy.$toast('请选择报图日期')
                return
              } 
              if (none.includes(d.lastReportPicArea)) {
                proxy.$toast('请填写报图面积')
                return
              }*/
            } else {
              data.lastReportPicTime = ''
              data.lastReportPicArea = ''
            }
            console.log(attrachRequired, data)
            if (attrachRequired.value) {
              if (!data.attachmentDTOS) {
                proxy.$toast('请上传解冻附件')
                return
              }
            }
          }
        }

        data.schedule = schedule
        saveOrSubmit(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast(schedule === 'B' ? '提交成功' : '保存成功')
              proxy.$SimpleEvents.emit('refreshCustomerChangeItem', data.id)
              if (callback) {
                callback()
                return
              }
              nextTick(() => {
                $router.goBack()
              })
            } else {
              proxy.$toast(res.msg || '操作失败')
            }
          })
          .catch((error) => {
            proxy.$toast(error || '操作失败')
          })
      }
      const onView = () => {
        onSave('A', () => {
          $router.push({
            path: '/dealerFreezeAndthaw/preview',
            query: {
              id: `${datas.id}`
            }
          })
        })
      }

      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }

      const onSearchCustomerManager = () => {
        const officeCode = dealerData.value.officeCode
        const customerCode = datas.detail?.customerCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('FreezeAndthawAddSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/customerManager',
          query: {
            name: 'FreezeAndthawAddSetManager',
            office: officeCode,
            customer: customerCode
          }
        })
      }
      const getDetail = async () => {
        const id = `${datas.id}`
        detail(id).then((res) => {
          const d = res.data
          datas.detail = d
          initFormData(d, datas.formData)
          const freezeDTO: anyObjectModle = { changeCode: d.code }
          datas.freezeDTO = { ...datas.freezeDTO, ...freezeDTO }
          if (d.freezeDTO) {
            datas.freezeDTO = { ...datas.freezeDTO, ...d.freezeDTO }
            datas.freezeDTO.isInvolveDeposit = [1, '1'].includes(d.freezeDTO.isInvolveDeposit)
            datas.freezeDTO.isInvolveReportPic = [1, '1'].includes(d.freezeDTO.isInvolveReportPic)
            if (datas.freezeDTO.executeTime) {
              datas.freezeDTO.executeTime = parseTime(datas.freezeDTO.executeTime, '{y}-{m}-{d}')
            }
            datas.freezeDTO.isTempUnfreeze = [1, '1'].includes(d.freezeDTO.isTempUnfreeze)
            if (datas.freezeDTO.preCloseTime) {
              datas.freezeDTO.preCloseTime = parseTime(datas.freezeDTO.preCloseTime, '{y}-{m}-{d} {h}:{i}:{s}')
            }
            if (datas.freezeDTO.lastReportPicTime) {
              datas.freezeDTO.lastReportPicTime = parseTime(datas.freezeDTO.lastReportPicTime, '{y}-{m}-{d}')
            }
            /* if (none.includes(datas.freezeDTO.reportType)) {
              datas.freezeDTO.reportType = 'A'
            } */
          }

          let checkedAccountCodes = []
          if (d.rangeDTOS && d.rangeDTOS.length) {
            checkedAccountCodes = d.rangeDTOS
              .filter((v: any) => [1, '1'].includes(v.isChange))
              .map((v: any) => v.accountCode)
          }
          datas.checkedAccountCodes = checkedAccountCodes
        })
      }
      const getCheckDisable = (state: any) => {
        // state ： 账号是否冻结：1/0
        if (typeCode.value === 'F') {
          // 解冻操作，正常状态不可选
          return ![1, '1'].includes(state)
        } else {
          // 冻结操作，已冻结状态不可选
          return [1, '1'].includes(state)
        }
      }
      // 冻结/解冻类型 数据变更
      const handleChangeType = () => {
        if (datas.freezeDTO.subType) datas.freezeDTO.subType = ''
      }

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (!['DealerInfoFreezeAndthaw', 'DealerFreezeAndthawDetail'].includes(toName)) {
          $store.commit('routerKeep/resetCache', instanceName)
        } else {
          $store.commit('routerKeep/removeCache', instanceName)
        }
      })

      const date = new Date()
      const sDate = new Date().setMonth(date.getMonth() - 1)
      const eDate = new Date().setMonth(date.getMonth() + 2)
      datas.minDate = new Date(sDate)
      datas.maxDate = new Date(eDate)

      getDetail()
      return {
        ...toRefs(datas),
        typeCode,
        typeName,
        dealerData,
        onView,
        onSave,
        onSearchCustomerManager,
        accountList,
        getCheckDisable,
        handleChangeType,
        attrachRequired
      }
    }
  }
</script>
<style lang="less" scoped>
  .account-list {
    padding: 0 16px;
    /deep/ .qmp-checkbox__label {
      flex: 1;
    }
    .account-item {
      padding: 16px 0;
      .title {
        margin-bottom: 2px;
        display: flex;
        align-items: center;
        .tag {
          display: inline-block;
          padding: 2px 4px;
          background: var(--bg-focusing-brand);
          border-radius: ' 2px 2px 2px 2px';
          border: 1px solid var(--button-main-default);
          font: var(--font-point);
          color: var(--texticon-color-brand-normal);
          margin-right: 4px;
        }
        .code {
          font: var(--font-main-title-strengthen);
          color: var(--texticon-default-strong);
        }
        .state {
          flex: 1;
          font: var(--font-main-body);
          text-align: right;
        }
      }
      .address {
        font: var(--font-main-title-body);
        color: var(--texticon-default-strong);
      }
    }
  }
  .requiredClass {
    position: relative;
    &::before {
      content: '*';
      position: absolute;
      left: 5px;
      top: 20px;
      color: var(--texticon-color-error-normal);
    }
  }
</style>
